package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.SerialKeys;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.MatrQbt;
import com.scs.application.modules.base.mapper.MatrQbtMapper;
import com.scs.application.modules.base.service.MatrQbtService;
import com.scs.application.modules.base.service.MatrService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 带量采购类型 服务实现类
 * </p>
 *
 * @author Auto Code
 * @since 2024-06-05
 */
@Service
public class MatrQbtServiceImpl extends BaseServiceImpl<MatrQbtMapper, MatrQbt> implements MatrQbtService {
    @Resource
    private MatrService matrService;
    @Override
    public boolean saveOrUpdate(MatrQbt entity) {
        if (entity.isNewRecord()) {
            entity.setTypeCode(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.MATR_QBT));
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        List<String> codeList = this.list(Wrappers.<MatrQbt>query().in("id", idList)).stream().map(MatrQbt::getTypeCode).collect(Collectors.toList());
        Matr matr = matrService.getOne(Wrappers.<Matr>query().in("matr_qbt_code", codeList).last("limit 1"));
        if (matr != null) {
            throw new BusinessException("该类型已有商品[%s]使用，不允许删除",matr.getName());
        }
        return super.removeCascadeByIds(idList);
    }
}
